#include "Common.hpp"
#include "InetAddr.hpp"

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " server_ip server_port" << std::endl;
}

// ./tcpclient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 1. 创建套接字文件
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket error";
        exit(SOCKET_ERR);
    }
    LOG(LogLevel::INFO) << "socket success";

    // 2. 直接向目标服务器发起建立连接的请求
    InetAddr serverAddr(server_ip, server_port);
    int n = connect(sockfd, serverAddr.NetAddrPtr(), serverAddr.NetAddrLen());
    if (n < 0)
    {
        LOG(LogLevel::FATAL) << "connect error";
        exit(CONNECT_ERR);
    }
    LOG(LogLevel::INFO) << "connect success";

    // 3. echo client
    while (true)
    {
        // 3.1 发消息
        std::string line;
        std::cout << "Please Enter# ";
        std::getline(std::cin, line);
        if (line.empty())
            continue;
        write(sockfd, line.c_str(), line.size());

        // 3.2 收消息
        char buffer[1024];
        ssize_t s = read(sockfd, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << buffer << std::endl;
        }
    }
    return 0;
}